package gadgetwars.client;

import gadgetwars.client.GadgetWarsService;
import gadgetwars.client.GadgetWarsServiceAsync;
import gadgetwars.shared.DiggNews;
import gadgetwars.shared.AmazonData;
import gadgetwars.shared.YahooImage;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

//import com.google.gwt.search.client.*;
//import com.google.gwt.search.client.SearchResultsHandler.SearchResultsEvent;
/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GadgetWars implements EntryPoint {
	
	private GadgetWarsServiceAsync gadgetwarsService = GWT.create(GadgetWarsService.class);
	private Button sendButton = new Button("Vs.");
	SuggestBox gadget1;
	SuggestBox gadget2;
	private String input1;
	private String input2;
	private TabPanel leftTabPanel = new TabPanel();
	private TabPanel rightTabPanel = new TabPanel();	
	private int leftTabIndex;
	private int rightTabIndex;
	private FlowPanel leftTabSubPanel1 = new FlowPanel();
	private FlowPanel leftTabSubPanel2 = new FlowPanel();
	private FlowPanel rightTabSubPanel1 = new FlowPanel();
	private FlowPanel rightTabSubPanel2 = new FlowPanel();
		
	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel searchPanel = new HorizontalPanel();
	private HorizontalPanel contentPanel = new HorizontalPanel();
	private VerticalPanel leftContentPanel= new VerticalPanel();
	private VerticalPanel paddingPanel= new VerticalPanel();
	private VerticalPanel rightContentPanel= new VerticalPanel();
	
	//private HorizontalPanel tabPanel = new HorizontalPanel();
	//private HorizontalPanel diggPanel = new HorizontalPanel();	
	private ScrollPanel leftDiggPanel = new ScrollPanel();
	private ScrollPanel rightDiggPanel = new ScrollPanel();
	
	private YahooImage myYahooImage1;
	private YahooImage myYahooImage2;
	private DiggNews[] myDiggNews1;
	private DiggNews[] myDiggNews2;
	private AmazonData myAmazonData1;
	private AmazonData myAmazonData2;
	
	private static String[] gadgetNames;
	private static Boolean initialFlag = false;
	
	   	   
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		if(initialFlag==false){ insertInitialData(); initialFlag=true;}
		getGadgetNames();
	}
	
	private void loadPage(){
		final MultiWordSuggestOracle oracle1 = new MultiWordSuggestOracle();
		gadget1 = new SuggestBox(oracle1);
		final MultiWordSuggestOracle oracle2 = new MultiWordSuggestOracle();
		gadget2 = new SuggestBox(oracle2);
		for(String gadgetName: gadgetNames){
			oracle1.add(gadgetName);
			oracle2.add(gadgetName);
		}

		gadget1.setFocus(true);
		gadget1.addStyleName("leftTextBox"); //Red
		gadget2.addStyleName("rightTextBox"); //Blue
		sendButton.addStyleName("gwt-Button sendButton");

		searchPanel.add(gadget1);		
		searchPanel.add(sendButton);
		searchPanel.add(gadget2);
		searchPanel.addStyleName("searchPanel");

		leftContentPanel.addStyleName("leftContent");
		rightContentPanel.addStyleName("rightContent");
		

		leftTabSubPanel1.addStyleName("tabHeight");
		leftTabSubPanel2.addStyleName("tabHeight");
		rightTabSubPanel1.addStyleName("tabHeight");	
		rightTabSubPanel2.addStyleName("tabHeight");	

		rightTabPanel.addStyleName("blueTabPanel");
		leftTabPanel.addStyleName("redTabPanel");

		leftDiggPanel.addStyleName(" halfWidth block");
		rightDiggPanel.addStyleName(" halfWidth block");
		paddingPanel.addStyleName("paddingPanel");
		mainPanel.add(searchPanel);
		mainPanel.add(contentPanel);
		contentPanel.add(leftContentPanel);
		contentPanel.add(paddingPanel);
		contentPanel.add(rightContentPanel);
		mainPanel.addStyleName("mainPanel");
	    RootPanel.get("gadgetInfo").add(mainPanel);
		
		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);	
	}
	
	private void getDiggNews(String gadget, String sortOrder,final int gadgetIndex){
		sortOrder = "diggs"; //sortOrder = date or diggs
		if(gadgetwarsService == null)
			gadgetwarsService = GWT.create(GadgetWarsService.class);
		AsyncCallback<DiggNews[]> callback = new AsyncCallback<DiggNews[]>(){
			public void onFailure(Throwable caught) {
				if(gadgetIndex==1) displayErrorMessage(leftDiggPanel, "There was an error in retreiving Digg Information");
				if(gadgetIndex==2) displayErrorMessage(rightDiggPanel, "There was an error in retreiving Digg Information");
			}

			public void onSuccess(DiggNews[] diggNews) {
				if(gadgetIndex==1){
					try{
						myDiggNews1 = diggNews;
						displayDiggNewsData(myDiggNews1,1);			
					}catch(Exception e){
						displayErrorMessage(leftDiggPanel, "Time out. Try Again.");
					}
				}
				if(gadgetIndex==2){
					try{
						myDiggNews2 = diggNews;
						displayDiggNewsData(myDiggNews2,2);					
					}catch(Exception e){
						displayErrorMessage(rightDiggPanel, "Time out. Try Again.");
					}
				}
			}
		};
		gadgetwarsService.getDiggNews(gadget, sortOrder, gadgetIndex, callback);
		
	}	
/*	
	private FlexTable getGoogleImageData(String gadget) {
	      SearchControlOptions options = new SearchControlOptions();
	      ImageSearch imageSearch = new ImageSearch();
	      options.add(imageSearch);
	      final FlexTable resultsTable = new FlexTable();
	      final SearchControl control = new SearchControl(options);
	      control.addSearchResultsHandler(new SearchResultsHandler() {
		        public void onSearchResults(SearchResultsEvent event) {
		          JsArray<? extends Result> results = event.getResults();

		          for (int i = 0; i < results.length(); i++) {
		            if (results.get(i).getResultClass().equals(
		                ResultClass.IMAGE_SEARCH_RESULT)) {
		              ImageResult result = (ImageResult) results.get(i);
		              resultsTable.setHTML(i, 0,result.getResultClassString());
		            }
		          }
		        }

		      }
	      );
	      
		//imageSearch.setNoHtmlGeneration();
		
		return resultsTable;
	}
*/	
	private void getAmazonData(String gadget, final int gadgetIndex){
		if(gadgetwarsService == null)
			gadgetwarsService = GWT.create(GadgetWarsService.class);
		AsyncCallback<AmazonData> callback = new AsyncCallback<AmazonData>(){
			public void onFailure(Throwable caught) {
				if(gadgetIndex==1){
					leftTabSubPanel1.clear();
					displayErrorMessage(leftTabSubPanel1, "There was an error in retreiving Amazon data");
					}
				if(gadgetIndex==2){
					rightTabSubPanel1.clear();
					displayErrorMessage(rightTabSubPanel1, "There was an error in retreiving Amazon data");
					}
				
				}

			public void onSuccess(AmazonData amazonData) {
				
				if(gadgetIndex==1){
					try{
						myAmazonData1 = amazonData;
						//amazonData.printAmazonData();						
						displayAmazonData(myAmazonData1,1);
					}catch(Exception e){
						//displayErrorMessage(leftTabSubPanel1, "There was an error in retreiving Amazon data");
					}
				}
				if(gadgetIndex==2){
					try{
						myAmazonData2 = amazonData;
						displayAmazonData(myAmazonData2,2);
					}catch(Exception e){
						//displayErrorMessage(rightTabSubPanel1, "There was an error in retreiving Amazon data");
					}					
				}
			}
			
		};
		gadgetwarsService.getAmazonData(gadget,gadgetIndex,callback);
	}
	
	
	private void getYahooImage(String gadget, final int gadgetIndex){
		if(gadgetwarsService == null)
			gadgetwarsService = GWT.create(GadgetWarsService.class);
		AsyncCallback<YahooImage> callback = new AsyncCallback<YahooImage>(){
			public void onFailure(Throwable caught) {
				if(gadgetIndex==1){
					leftTabSubPanel1.clear();
					displayErrorMessage(leftTabSubPanel2, "There was an error in retreiving Amazon data");
					}
				if(gadgetIndex==2){
					rightTabSubPanel1.clear();
					displayErrorMessage(rightTabSubPanel2, "There was an error in retreiving Amazon data");
					}
				
				}

			public void onSuccess(YahooImage yahooImage) {
				if(gadgetIndex==1){
					try{
						myYahooImage1 = yahooImage;
						yahooImage.printYahooImage();
						//displayYahooImage(yahooImage,gadgetIndex);
					}catch(Exception e){
						//displayErrorMessage(leftTabSubPanel1, "There was an error in retreiving Amazon data");
					}
				}
				if(gadgetIndex==2){
					try{
						myYahooImage2 = yahooImage;
						//displayYahooImage(yahooImage,gadgetIndex);
					}catch(Exception e){
						//displayErrorMessage(rightTabSubPanel1, "There was an error in retreiving Amazon data");
					}					
				}
			}
			
		};
		gadgetwarsService.getYahooImage(gadget,gadgetIndex,callback);
	}
		
	 class MyHandler implements ClickHandler{
		 
			public void onClick(ClickEvent event) {				
				clearPanels();
				addPanels();
				gadget1.setFocus(true);
				if("".equals(gadget1.getText()) && "".equals(gadget1.getText().trim())){
					return;
				}
				if( !gadget1.getText().equalsIgnoreCase(input1) )
				{						
					input1 = gadget1.getText().trim();

				}			
				if("".equals(gadget2.getText()) && "".equals(gadget2.getText().trim())){
					return;
				}
				if( !gadget2.getText().equalsIgnoreCase(input2) )
				{						
					input2 = gadget2.getText().trim();
				}
				
				
				leftTabSubPanel1.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));
				rightTabSubPanel1.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));
				leftTabPanel.selectTab(0);
				rightTabPanel.selectTab(0);
				leftDiggPanel.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));
				rightDiggPanel.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));
				getAmazonData(input1,1);
				getAmazonData(input2,2);
				getYahooImage(input1,1);
				getYahooImage(input2,2);
				getDiggNews(input1,"diggs" ,1);
				getDiggNews(input2,"diggs" ,2);
			}
		}
	 
	 
	 
		private void displayDiggNewsData(DiggNews[] dgNews,int gadgetIndex)
		{
			if(gadgetIndex==1){
				leftDiggPanel.clear();
				VerticalPanel leftVerticalPanel = new VerticalPanel();
				HTML title = new HTML("<span class=\"newstitle\">Digg</span>&nbsp<span class=\"newstitle\">News</span>");
				leftVerticalPanel.add(title);
				HTML news;	    
				for(int i = 0; i < dgNews.length; i++)
				{
					String desc = dgNews[i].getDescription();
					if(desc.length() > 200)
					{
						desc = desc.substring(0, 200);
						desc += "...";												
					}
					news = new HTML("<a href=" + dgNews[i].getUrl() + " color=#00008B target=\"_blank\">" + dgNews[i].getTitle() + "</a></br>&nbsp;" + desc);
					news.addStyleName("block textHTML");
					leftVerticalPanel.add(news);
				}
				leftDiggPanel.add(leftVerticalPanel);							
			}
			if(gadgetIndex==2){
				rightDiggPanel.clear();
				VerticalPanel rightVerticalPanel = new VerticalPanel();
				HTML title = new HTML("<span class=\"newstitle2\">Digg</span>&nbsp<span class=\"newstitle2\">News</span>");
				rightVerticalPanel.add(title); 
				HTML news;	    
				for(int i = 0; i < dgNews.length; i++)
				{
					String desc = dgNews[i].getDescription();
					if(desc.length() > 200)
					{
						desc = desc.substring(0, 200);
						desc += "...";												
					}
					news = new HTML("<a href=" + dgNews[i].getUrl() + " color=#00008B target=\"_blank\">" + dgNews[i].getTitle() + "</a></br>&nbsp;" + desc);
					news.addStyleName("block textHTML");
					rightVerticalPanel.add(news);
				}
				rightDiggPanel.add(rightVerticalPanel);	
				
			}
		}
		
		private void displayAmazonData(AmazonData amazonData, int gadgetIndex)
		{
			if(gadgetIndex==1){
				leftTabSubPanel1.clear();							
				VerticalPanel lVerticalPanel = new VerticalPanel();			
				HorizontalPanel hPanel = new HorizontalPanel();
				HTML priceInfo = new HTML("<div class=\"textHTML\"><a href=\"" + amazonData.getitem_PageURL() + "\" target=\"_blank\">" + amazonData.getitem_Title() + "<br/></a><span class=\"price\">Price: US" + amazonData.getitem_LowestNewPrice() + "</span></div>");
				priceInfo.setWidth("330px");								
				hPanel.add(priceInfo);				
				lVerticalPanel.add(hPanel);
				HTML iframeUrl = new HTML("<iframe width=\"480\" height=\"200\" src=\"" + amazonData.getitem_IFrameURL() + "\"></iframe>");			
				lVerticalPanel.add(iframeUrl);				
				leftTabSubPanel1.add(lVerticalPanel);
				leftTabPanel.selectTab(0);
			}
			if(gadgetIndex==2){
				rightTabSubPanel1.clear();			
				VerticalPanel lVerticalPanel = new VerticalPanel();			
				HorizontalPanel hPanel = new HorizontalPanel();
				HTML priceInfo = new HTML("<div class=\"textHTML\"><a href=\"" + amazonData.getitem_PageURL() + "\" target=\"_blank\">" + amazonData.getitem_Title() + "<br/></a><span class=\"price\">Price: US" + amazonData.getitem_LowestNewPrice() + "</span></div>");
				priceInfo.setWidth("330px");				
				hPanel.add(priceInfo);		
				lVerticalPanel.add(hPanel);
				HTML iframeUrl = new HTML("<iframe width=\"480\" height=\"200\" src=\"" + amazonData.getitem_IFrameURL() + "\"></iframe>");				
				lVerticalPanel.add(iframeUrl);				
				rightTabSubPanel1.add(lVerticalPanel);
				rightTabPanel.selectTab(0);
				
			}
		}
		
		
		private void displayYahooImage(YahooImage yahooImage, int gadgetIndex)
		{
			ScrollPanel scPanel = new ScrollPanel();
			scPanel.setStyleName("halfWidth");
			if(gadgetIndex==1){
				leftTabSubPanel2.clear();								
				HorizontalPanel hPanel = new HorizontalPanel();	
				for(int i=0;i<10;i++){
					Image yImage = new Image(yahooImage.getImageUrl()[i]);			
					yImage.addStyleName("image");
					hPanel.add(yImage);									
				}
				scPanel.add(hPanel);
				leftTabSubPanel2.add(scPanel);
				leftTabPanel.selectTab(1);
			}
			if(gadgetIndex==2){
				rightTabSubPanel2.clear();								
				HorizontalPanel hPanel = new HorizontalPanel();	
				for(int i=0;i<10;i++){
					Image yImage = new Image(yahooImage.getImageUrl()[i]);	
					yImage.addStyleName("image");
					hPanel.add(yImage);						
				}
				scPanel.add(hPanel);
				rightTabSubPanel2.add(scPanel);
				rightTabPanel.selectTab(1);
				
			}
		}
		
	   
		  public void clearPanels(){
			    leftContentPanel.clear();
				leftTabPanel.clear();
				rightTabPanel.clear();
				rightContentPanel.clear();
				leftDiggPanel.clear();
				rightDiggPanel.clear();
		   }		  
		  public void addPanels(){
			  	leftContentPanel.add(leftTabPanel);
			  	rightContentPanel.add(rightTabPanel);
				leftContentPanel.add(leftDiggPanel);
				rightContentPanel.add(rightDiggPanel);
				leftTabPanel.add(leftTabSubPanel1,"AMAZON");
				leftTabPanel.add(leftTabSubPanel2,"IMAGE");
				rightTabPanel.add(rightTabSubPanel1,"AMAZON");
				rightTabPanel.add(rightTabSubPanel2,"IMAGE");
				
				final int MAX_IMAGES = 4;

				leftTabPanel.addSelectionHandler(new SelectionHandler<Integer>(){ 
		            public void onSelection(SelectionEvent<Integer> event) {
		                if (event.getSelectedItem() != leftTabIndex) {
		                	leftTabIndex = event.getSelectedItem();
		                    
		                    switch(leftTabIndex)
		                    {
		                    case 0:
		                    	leftTabSubPanel1.clear();
		                    	leftTabSubPanel1.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));
		                    	displayAmazonData(myAmazonData1,1);
		                    	break;
		                    	
		                    case 1:
		                    	leftTabSubPanel2.clear();
		                    	leftTabSubPanel2.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));

		                    	displayYahooImage(myYahooImage1,1);
		                    	/*
		                    	FlexTable imagesLeft = getGoogleImageData(gadget1.getText());
		                    	for(int i=0; i<imagesLeft.getRowCount() && i<MAX_IMAGES;i++) {
		                    		leftTabSubPanel2.add(imagesLeft.getWidget(i, 0));
		                    	}
		                    	break;
		                    	*/		                    	
		                    }
		                }
		          }});
				rightTabPanel.addSelectionHandler(new SelectionHandler<Integer>(){ 
		            public void onSelection(SelectionEvent<Integer> event) {
		                if (event.getSelectedItem() != rightTabIndex) {
		                	rightTabIndex = event.getSelectedItem();
		                    
		                    switch(rightTabIndex)
		                    {
		                    case 0:
		                    	rightTabSubPanel1.clear();
		                    	rightTabSubPanel1.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));
		                    	displayAmazonData(myAmazonData2,2);
		                    	break;
		                    	
		                    case 1:
		                    	rightTabSubPanel2.clear();
		                    	rightTabSubPanel2.add(new Image("http://www.duravit.com/duravit/file/all/ani_loader_big2.gif"));

		                    	displayYahooImage(myYahooImage2,2);
		                    	/*
		                    	FlexTable imagesRight = getGoogleImageData(gadget2.getText());
		                    	for(int i=0; i<imagesRight.getRowCount() && i<MAX_IMAGES; i++) {
		                    		rightTabSubPanel2.add(imagesRight.getWidget(i, 0));
		                    	}
		                    	break;
		                    	*/
		                    	
		                    }
		                }
		          }});
		  }
		  
			private void displayErrorMessage(Panel panel, String errorMsg)
			{
				panel.clear();
				panel.add(new HTML("<font size=\"5px\" color=\"gray\">" + errorMsg + "</font>"));
			}
			
			private void insertInitialData() {
				try{
					if(gadgetwarsService == null)
						gadgetwarsService = GWT.create(GadgetWarsService.class);
					AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(){
						public void onFailure(Throwable caught) {
						}
			
						public void onSuccess(Boolean isSuccess) {
							try{
								System.out.println("Success in inserting the value? " + isSuccess);
							}catch(Exception e){
							}
						}
					};
					gadgetwarsService.insertInitialData(callback);
				}catch(Exception e){
				}
			}
			
			private void getGadgetNames()
			{
		        try {
		            if(gadgetwarsService == null)
		            	gadgetwarsService = GWT.create(GadgetWarsService.class);
		            AsyncCallback<String[]> callback = new AsyncCallback<String[]>(){
		                    public void onFailure(Throwable caught) {
		                    }

		                    public void onSuccess(String[] gadgetNames) {
		                            try{
		                            	GadgetWars.gadgetNames = gadgetNames;
		                            	loadPage();
		                            }catch(Exception e){
		                            }
		                    }
		            };
		            gadgetwarsService.getGadgetNames(callback);
		        }catch(Exception e){
		        }
			}
}
